//
//  HomeViewController.m
//  Project_2_weibo
//
//  Created by 林林 on 16/6/16.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "HomeViewController.h"
#import "AppDelegate.h"
#import "ThemeImageView.h"
#import "Weibo.h"
#import "User.h"
#import "WeiboCell.h"
#import "WeiboCellLayout.h"
#import "WXRefresh.h"
#import <AVFoundation/AVFoundation.h>
#import "CommentViewController.h"

@interface HomeViewController () <SinaWeiboRequestDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UITableView *_WeiboList;
    NSMutableArray *_weiboArr;
    SystemSoundID _msgSound;
}

@property (nonatomic, strong) ThemeImageView *weiboCountView;
@property (nonatomic, strong) ThemeLabel *weiboCountLabel;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"首页";
    
    //注册系统提示音
    [self registerSoundID];
    
    [self requestWeiboData];

    [self createTableView];
}

//发起微博请求
- (void)requestWeiboData {
    
    //获取当前微博对象
    SinaWeibo *weibo = kWeiboObject;
    
    //判断微博是否已经登录
    if ([weibo isAuthValid]) {
        
        NSMutableDictionary *params = [@{@"count" : @"20"} mutableCopy];
        //发起请求
        SinaWeiboRequest *request =  [weibo requestWithURL:@"statuses/friends_timeline.json"
                       params:params
                   httpMethod:@"GET"
                     delegate:self];
        //添加微博请求tag
        request.tag = 1;
    }else {
        //进行登录
        [weibo logIn];
    }
    
}

//创建表视图
- (void)createTableView {
    
    _WeiboList = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 49) style:UITableViewStylePlain];
    _WeiboList.backgroundColor = [UIColor clearColor];
    _WeiboList.delegate = self;
    _WeiboList.dataSource = self;
    
    //注册单元格
    UINib *weiboNib = [UINib nibWithNibName:@"WeiboCell" bundle:[NSBundle mainBundle]];
    [_WeiboList registerNib:weiboNib forCellReuseIdentifier:@"WeiboCell"];
    
    [self.view addSubview:_WeiboList];
    
    //防止block的循环引用
    __weak HomeViewController *weakSelf = self;
    
    //添加下拉刷新和上拉加载更多
    [_WeiboList addPullDownRefreshBlock:^{
        NSLog(@"下拉刷新");
        //防止self释放时weakself为空
        __strong HomeViewController *strongSelf = weakSelf;
        [strongSelf loadNewWeibo];
    }];
    
    [_WeiboList addInfiniteScrollingWithActionHandler:^{
        NSLog(@"上拉加载更多");
        //防止self释放时weakself为空
        __strong HomeViewController *strongSelf = weakSelf;
        [strongSelf loadMoreWeibo];
    }];
    
}

#pragma mark - 注册系统提示音
- (void)registerSoundID {
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"msgcome" withExtension:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &_msgSound);
}

- (void)dealloc {
    //移除音频
    AudioServicesRemoveSystemSoundCompletion(_msgSound);
}
#pragma mark - 更新微博数量
- (ThemeImageView *)weiboCountView {
    
    if (_weiboCountView == nil) {
        _weiboCountView = [[ThemeImageView alloc] initWithFrame:CGRectMake(5, -45, kScreenWidth - 10, 40)];
        _weiboCountView.imageName = @"timeline_notify.png";
        //默认影藏
        _weiboCountView.hidden = YES;
        [self.view addSubview:_weiboCountView];
    }
    return _weiboCountView;
}

- (ThemeLabel *)weiboCountLabel {
    
    if (_weiboCountLabel == nil) {
        _weiboCountLabel = [[ThemeLabel alloc] initWithFrame:self.weiboCountView.bounds];
        _weiboCountLabel.colorName = @"Mask_Noitce_color";
        _weiboCountLabel.textAlignment = NSTextAlignmentCenter;
        
        [self.weiboCountView addSubview:_weiboCountLabel];
    }
    return _weiboCountLabel;
}

#pragma mark - 显示更新微博数量的视图
- (void)showWeiboCount:(NSInteger)count {
    
//    if (count <= 0) {
//        return;
//    }
    
    //显示更新微博数量
    self.weiboCountView.top = -45;
    self.weiboCountView.hidden = NO;
    self.weiboCountLabel.text = [NSString stringWithFormat:@"%li条微博", count];
    
    if (count <= 0) {
        self.weiboCountLabel.text = @"没有新微博";
    }
    //动画
    [UIView animateWithDuration:0.5 animations:^{
        self.weiboCountView.top = 5;
    } completion:^(BOOL finished) {
        AudioServicesPlaySystemSound(_msgSound);
        //延迟再上移
        [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionLayoutSubviews animations:^{
            _weiboCountView.top = -45;
        } completion:nil];
    }];
    
}


#pragma mark - 下拉刷新和上拉加载更多

- (void)loadNewWeibo {
    
    //获取当前微博对象
    SinaWeibo *weibo = kWeiboObject;
    
    if (![weibo isAuthValid]) {
        [weibo logIn];
        return;
    }
    
    //获取第一条微博
    Weibo *firstWeibo = [_weiboArr firstObject];
    if (firstWeibo == nil) {
        //当前还没有微博数据
        [self requestWeiboData];
        return;
    }
    
    NSDictionary *pramas = @{@"count" : @"20",
                             @"since_id" : firstWeibo.idstr};
    
    SinaWeiboRequest *request = [weibo requestWithURL:@"statuses/friends_timeline.json" params:[pramas mutableCopy] httpMethod:@"GET" delegate:self];
    request.tag = 2;
}

- (void)loadMoreWeibo {
    
    //获取当前微博对象
    SinaWeibo *weibo = kWeiboObject;
    
    if (![weibo isAuthValid]) {
        [weibo logIn];
        return;
    }
    
    //获取最后一条微博
    Weibo *lastWeibo = [_weiboArr lastObject];
    if (lastWeibo == nil) {
        //当前还没有微博数据
        [self requestWeiboData];
        return;
    }
    
    NSInteger maxID = [lastWeibo.idstr integerValue];
    maxID--;
    
    NSDictionary *pramas = @{@"count" : @"20",
                             @"max_id" : [NSString stringWithFormat:@"%li", maxID]};
    
    SinaWeiboRequest *request = [weibo requestWithURL:@"statuses/friends_timeline.json" params:[pramas mutableCopy] httpMethod:@"GET" delegate:self];
    request.tag = 3;
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _weiboArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WeiboCell"];
    
    cell.weiboModel = _weiboArr[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Weibo *w = _weiboArr[indexPath.row];
    WeiboCellLayout *layout = [WeiboCellLayout weiboCellLayoutWithWeiboModel:w];
    return layout.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentViewController *cVc = [[CommentViewController alloc] init];
    cVc.weibo = _weiboArr[indexPath.row];
    cVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cVc animated:YES];
    
}

#pragma mark - SinaWeibo Request Delegate
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
//    NSLog(@"%@", result);
    
    NSArray *statuses = result[@"statuses"];
    NSMutableArray *mArr = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in statuses) {
        
        Weibo *w = [Weibo yy_modelWithJSON:dic];
        [mArr addObject:w];
    }
    
    //判断请求的类型
    if (request.tag == 1) {
        //请求方式1,直接加载新的数据
        _weiboArr = [mArr mutableCopy];
        
    }else if (request.tag == 2) {
        //方式2,加载最新微博
        [_weiboArr insertObjects:mArr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, mArr.count)]];
        [self showWeiboCount:mArr.count];
    }else if (request.tag == 3) {
        //方式3,加载更多微博
        [_weiboArr addObjectsFromArray:mArr];
    }
    //刷新表视图
    [_WeiboList reloadData];
    //停止动画
    [_WeiboList.pullToRefreshView stopAnimating];
    [_WeiboList.infiniteScrollingView stopAnimating];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end













